package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Role;
import cn.wolfcode.mapper.RoleMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    //private static final Logger log = LoggerFactory.getLogger(RoleServiceImpl.class);

    @Override
    public int deleteByPrimaryKey(Long id) {
        return roleMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void insert(Role record, Long[] permissionIds) {
        // 添加角色数据
        roleMapper.insert(record);
        // 往中间表录入数据
        saveRelation(record, permissionIds);
    }

    private void saveRelation(Role record, Long[] permissionIds) {
        if (permissionIds != null && permissionIds.length > 0) {
            for (Long permissionId : permissionIds) {
                roleMapper.insertRelation(record.getId(), permissionId);
            }
        }
    }

    @Override
    public Role selectByPrimaryKey(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Role> selectAll() {
        return roleMapper.selectAll();
    }

    @Override
    public List<Role> queryRoleLByEmployeeId(Long employeeId) {
        return roleMapper.selectRoleLByEmployeeId(employeeId);
    }

    @Override
    public void updateByPrimaryKey(Role record, Long[] permissionIds) {
        // 修改角色数据
        roleMapper.updateByPrimaryKey(record);
        // 修改角色权限中间表数据
        // 删除原数据 , 新增修改数据
        roleMapper.deleteAllByRoleId(record.getId());
        saveRelation(record, permissionIds);
    }

    @Override
    public PageInfo<Role> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Role> roles = roleMapper.selectForList(qo);
        return new PageInfo<>(roles);
    }



}
